# 面试算法题
# 使用Qwen/Qwen3-30B-A3B
import json
import sys

import requests
from openai import OpenAI


class CodeAgent:
    def __init__(self,position):
        self.position = position
        self.question = []
        self.answer = []
        self.message = [] # 模型回答上下文
        self.content = ''
        self.code = ''
        self.url = "https://api.siliconflow.cn/v1/chat/completions"
        self.headers = {
            "Authorization": "Bearer sk-aepgqkfvmurbvuorsdddujpstjvmgjjldiuosmcwhfoaplhu",
            "Content-Type": "application/json"
        }
        self.payload = {
            # "model": "Qwen/QwQ-32B",
            "model": "Qwen/Qwen3-14B",
            "messages": self.message,
            "stream": False,
            "max_tokens": 512,
            "min_p": 0.05,
            "stop": None,
            "temperature": 0.7,
            "top_p": 0.7,
            "top_k": 50,
            "frequency_penalty": 0.5,
            "n": 1,
            "response_format": {"type": "text"},
        }
        self.client = OpenAI(api_key="sk-829463e11b81404a8e2c1c8b2e3cad47", base_url="https://api.deepseek.com") # 评价代码的模型

    # 生成面试题
    def generate_code(self):
        print("根据岗位生成面试算法题中。。。")
        # self.model = "Qwen/QwQ-32B"
        # self.model = "Qwen/Qwen3-30B-A3B"
        self.message.append({
            "role": "user",
            "content": (
                f"你是一个经验丰富的算法面试官，擅长为技术岗位设计面试题。\n"
                f"面试者当前应聘的岗位是：{self.position}。\n"
                f"请基于该岗位的常见技术要求，出一道算法题，风格类似于 LeetCode。\n"
                f"要求：\n"
                f"1. 输出内容为 JSON 格式，包含两个字段：'content' 表示题目描述，'code' 表示需要面试者补全的函数代码框架，使用markdown格式输出。\n"
                f"2. 题目应与岗位强相关，例如前端开发偏向逻辑处理、字符串或事件流处理，后端开发偏向数据结构，动态规划，二叉树等。\n"
                f"3. 不要输出多余内容，只返回符合格式的 JSON。\n\n"
                f"返回示例：\n"
                f'{{\n  "content": "请实现一个函数，判断一个字符串中的括号是否成对匹配。",\n  "code": "def isValidParentheses(s: str) -> bool:\\n    # 请在此补全代码"\n}}'
            )
        })
        response = requests.request("POST", self.url, json=self.payload, headers=self.headers)
        print("原始响应",response.text)
        # 解析JSON并提取content和code
        result = response.json()
        message_text = result["choices"][0]["message"]["content"]
        message_text = message_text.replace("`","").replace("json","")
        # 如果 content 是 JSON 字符串，解析它
        content_json = json.loads(message_text)

        content = content_json.get("content", "")
        code = content_json.get("code", "")
        self.content = content
        self.code = code

        print("\n✅ 题目内容:")
        print(content)

        code = f"```\n{code}\n```"
        print("\n💻 代码框架:")
        print(code)
        return content, code

    def analyzeAns(self,answer):
        prompt = (
            f"面试者针对题目{self.question}所编写的代码是{answer},请对面试者的代码做出点评，分析其好的方面和需要改进的地方,并对面试者代码水平打分，满分100分，只要不是很差打分尽量80~90，只有非常好才能90~95，不能超过95"
            f"返回示例:"
            f'{{"advantage": "面试者所写的代码的优点。",  "advice": "需要改进优化的地方"，"score":"面试者代码水平打分"}}'
            )
        response = self.client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system",
                 "content": "你是一个计算机行业的面试官，擅长对面试者写的代码进行分析"},
                {"role": "user", "content": prompt},
            ],
            stream=False
        )
        evaluation = response.choices[0].message.content.replace("`", "").replace("json", "")
        evaluation = json.loads(evaluation)
        advantage = evaluation["advantage"]
        advice = evaluation["advice"]
        score = evaluation["score"]
        print("advantage",evaluation["advantage"])
        print("advice",evaluation["advice"])
        print("score",evaluation["score"])
        return advantage, advice, score


if __name__ == '__main__':
    codeAgent = CodeAgent("java后端工程师")
    codeAgent.generate_code()
    answer = input("回答：")
    codeAgent.analyzeAns(answer)